import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'

// 二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
// 导航守卫
// 需要拦截的页面
const loginURL = ['/user']
router.beforeEach(function (to, from, next) {
  const token = store.state.user.token.token
  // console.log(token)

  if (token) {
    next()
  } else {
    if (loginURL.some((item) => to.path === item)) {
      router.push('/login')
    } else {
      next()
    }
  }
})

export default router
